package com.h117121.fashionshop.servletfilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.h117121.fashionshop.constant.AppConstant;
import com.h117121.fashionshop.core.service.BusinessService;

@Component("dataContructorInterceptor")
public class DataContructor extends HandlerInterceptorAdapter {
	@Autowired
	private BusinessService businessService;

	/**
	 * Default constructor.
	 */
	public DataContructor() {
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (request instanceof HttpServletRequest) {
			if (((HttpServletRequest) request).getServletPath().equals(
					"/product")) {
				if (request.getParameter("id") != null) {
					long id = Long.parseLong(request.getParameter("id"));
					request.setAttribute(
							"similarProducts",
							businessService.getSimilarProducts(id, 0,
									AppConstant.NUM_SIMILAR_ITEM).getResult());
				}
			} else if (((HttpServletRequest) request).getServletPath().equals(
					"/home")) {
				request.setAttribute(
						"allProducer",
						businessService.getAllProducer(0,
								AppConstant.NUM_MAX_ITEM_LIST_LEFTPANEL)
								.getResult());
				request.setAttribute(
						"allProductType",
						businessService.getAllProductType(0,
								AppConstant.NUM_MAX_ITEM_LIST_LEFTPANEL)
								.getResult());

				request.setAttribute("similarProducts", businessService
						.getRandomProducts(AppConstant.NUM_SIMILAR_ITEM));
			}
		}

		return true;
	}
}
